<template>
  <div class="digital-flop-single-wrap" :style="containerStyle">
    <div class="digital-flop-inside-wrap" :style="insideStyle">
      <div class="digital-flop-single__item" :style="itemStyle" v-for="num in '0123456789'" :key="num">{{ num }}</div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'FlopItem',
  props: {
    number: {
      default: 0
    },
    width: {
      type: Number,
      default: 30
    },
    height: {
      type: Number,
      default: 40
    },
    fontSize: {
      type: Number,
      default: 28
    },
    backgroundColor: {
      type: String,
      default: '#1777CE'
    },
    color: {
      type: String,
      default: '#ffffff'
    },
    position: {
      type: Number,
      default: 2
    }
  },
  data() {
    return {
      current: 0,// 当前数字/上一次数字
      target: 0// 目标数字
    }
  },
  computed: {
    transform: function() {
      const p = this.height * this.target
      return `translateY(-${p}px)`
    },
    transition: function() {
      const t = Math.abs(this.target - this.current) / 5
      return `transform ${t}s ease-out`
    },
    containerStyle: function() {
      return {
        width: `${this.width}px`,
        height: `${this.height}px`,
        margin: `0 ${this.position}px`
      }
    },
    insideStyle: function() {
      return {
        width: `${this.width}px`,
        height: `${this.height * 10}px`,
        transform: this.transform,
        transition: this.transition
      }
    },
    itemStyle: function() {
      return {
        width: `${this.width}px`,
        height: `${this.height}px`,
        fontSize: `${this.fontSize}px`,
        backgroundColor: this.backgroundColor,
        color: this.color,
      }
    }
  },
  watch: {
    'number': function(newValue, oldValue) {
      if (typeof newValue === 'number' && typeof oldValue === 'number') {
        this.current = oldValue
        this.target = newValue
      } else {
        try {
          this.current = parseInt(oldValue)
          this.target = parseInt(newValue)
        } catch (e) {
          console.error('组件数据转换异常: ', e)
          console.error('原始数据为: ', this.number)
          this.current = 0
          this.target = 0
        }
      }
    }
  },
  mounted() {
    this.current = 0
    if (typeof this.number === 'number') {
      this.target = this.number
    } else {
      this.target = parseInt(this.number)
    }
  }
}
</script>

<style scoped lang="scss">
.digital-flop-single-wrap {
  overflow: hidden;

  .digital-flop-inside-wrap {
    transition-delay: 0.3s;

    .digital-flop-single__item {
      display: flex;
      align-items: center;
      justify-content: center;
    }
  }
}
</style>
